

//Load the SDK Asynchronously
(function(d){
	var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
	if (d.getElementById(id)) {return;}
	js = d.createElement('script'); js.id = id; js.async = true;
	js.src = "//connect.facebook.net/en_US/all.js";
	ref.parentNode.insertBefore(js, ref);
}(document));


window.fbAsyncInit = function() {
	FB.init({
		//appId      : '312085422193186', // Example App
		appId      : '460504350662588', // AlessaBgLogin App
        channelUrl : '//www.alessa.bg/demo/modules/vs_fblogin/channel.php', // Channel File
        status     : true, // check login status
        cookie     : true, // enable cookies to allow the server to access the session
        xfbml      : true  // parse XFBML
	}); 
}	


// Permissions that are needed for the app
var permsNeeded = ['email', 'user_birthday'];


function vsFbLogin()
{
	FB.login(checkLoginStatus, {scope: permsNeeded.join(',')});
}
//==================================================================================

function checkLoginStatus(response) {
    if(response && response.status == 'connected') {
    	fbGetUserInfo() ; 
    } else {
        alert('Not Authorized');
    }
}

function fbGetUserInfo() 
{
	FB.api('/me', function(user) {
		console.log(user);
		
		if (user) {	
			var imageSrc = 'https://graph.facebook.com/' + user.id + '/picture';
			/*
			 * Populate and submit the form
			 */
			$("input[name=email]").val(user.email);
			$("input[name=gender]").val(user.gender);
			$("input[name=first_name]").val(user.first_name);
			$("input[name=last_name]").val(user.last_name);
			$("input[name=name]").val(user.name);
			$("input[name=imageSrc]").val(imageSrc);
			$("input[name=birthday]").val(user.birthday);
			
			$("#formFbLogin").submit();
		}
	});
	
}
//======================================================================================

